using System;
using System.Windows;
using System.Collections.Generic;
using KeyAuthService.Dialogs;
using KeyAuthService.Models;
using Microsoft.Extensions.Logging;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.IO;
using System.Net;
using System.Linq;

namespace KeyAuthService.Services
{
    /// <summary>
    /// UI服务，用于显示对话框等UI操作
    /// </summary>
    public class UIService
    {
        private readonly ILogger<UIService> _logger;
        private readonly KeyStorageService _keyStorageService;

        public UIService(ILogger<UIService> logger, KeyStorageService keyStorageService)
        {
            _logger = logger;
            _keyStorageService = keyStorageService;
        }

        /// <summary>
        /// 在UI线程上执行操作
        /// </summary>
        private T InvokeOnUIThread<T>(Func<T> action)
        {
            if (Application.Current.Dispatcher.CheckAccess())
            {
                return action();
            }
            else
            {
                T result = default;
                Application.Current.Dispatcher.Invoke(() => result = action());
                return result;
            }
        }

        /// <summary>
        /// 显示确认对话框
        /// </summary>
        public bool ShowConfirmDialog(string message, string title = "确认", string confirmText = "确定", string cancelText = "取消", bool isWarning = false)
        {
            return InvokeOnUIThread(() =>
            {
                var dialog = new ModernConfirmDialog(message, title, confirmText, cancelText, isWarning);
                return dialog.ShowDialog() == true;
            });
        }

        /// <summary>
        /// 显示输入对话框
        /// </summary>
        public string ShowInputDialog(string message, string defaultValue = "", string title = "输入")
        {
            return InvokeOnUIThread(() =>
            {
                var dialog = new ModernInputDialog(message, title);
                if (dialog.ShowDialog() == true)
                {
                    return dialog.InputText;
                }
                return null;
            });
        }

        /// <summary>
        /// 显示消息框
        /// </summary>
        public void ShowMessageBox(string message, string title = "消息", MessageType type = MessageType.Info)
        {
            InvokeOnUIThread(() =>
            {
                ModernMessageBox.Show(message, title, type);
                return true;
            });
        }

        /// <summary>
        /// 显示成功消息
        /// </summary>
        public void ShowSuccess(string message, string title = "成功")
        {
            ShowMessageBox(message, title, MessageType.Success);
        }

        /// <summary>
        /// 显示错误消息
        /// </summary>
        public void ShowError(string message, string title = "错误")
        {
            ShowMessageBox(message, title, MessageType.Error);
        }

        /// <summary>
        /// 显示警告消息
        /// </summary>
        public void ShowWarning(string message, string title = "警告")
        {
            ShowMessageBox(message, title, MessageType.Warning);
        }

        /// <summary>
        /// 显示文本详情对话框
        /// </summary>
        public void ShowTextDetails(string text, string title = "详细信息")
        {
            InvokeOnUIThread(() =>
            {
                var dialog = new ModernTextDetailsWindow(title, text);
                dialog.ShowDialog();
                return true;
            });
        }

        /// <summary>
        /// 显示选择对话框
        /// </summary>
        public string ShowSelectionDialog(string prompt, string title, string[] items)
        {
            return InvokeOnUIThread(() =>
            {
                var dialog = new ModernSelectionDialog(prompt, title, items);
                if (dialog.ShowDialog() == true)
                {
                    return dialog.SelectedItem;
                }
                return null;
            });
        }

        /// <summary>
        /// 显示应用授权对话框
        /// </summary>
        public AppAuthorizationResult ShowAppAuthorizationDialog(AppInfo appInfo, List<string> requestedScopes)
        {
            return InvokeOnUIThread(() =>
            {
                try
                {
                    // 创建授权对话框内容
                    var appName = appInfo.app_name ?? "未知应用";
                    var appDeveloper = appInfo.developer ?? "未知开发者";
                    var appVersion = appInfo.app_version ?? "未知版本";
                    var appDescription = appInfo.description ?? "无描述";
                    
                    var message = new System.Text.StringBuilder();
                    message.AppendLine($"应用\"{appName}\"请求连接到KeyAuth服务");
                    message.AppendLine($"开发者: {appDeveloper}");
                    message.AppendLine($"版本: {appVersion}");
                    message.AppendLine($"描述: {appDescription}");
                    message.AppendLine();
                    message.AppendLine("请求的权限范围:");
                    
                    foreach (var scope in requestedScopes)
                    {
                        message.AppendLine($"• {TranslateScopeName(scope)}");
                    }
                    message.AppendLine();
                    message.AppendLine("注意: 授权将与连接绑定，断开连接后将自动撤销授权");

                    // 准备可选的密钥列表
                    var availableKeys = _keyStorageService.GetAllKeys();
                    var keyOptions = availableKeys.Where(k => !k.Revoked).Select(k => k.KeyName).ToArray();
                    var keyInfoMap = availableKeys.Where(k => !k.Revoked)
                                             .ToDictionary(k => k.KeyName, k => k);

                    // 显示确认对话框
                    if (ShowConfirmDialog(message.ToString(), "应用授权请求", "授权", "拒绝", true))
                    {
                        // 如果用户确认授权，选择密钥
                        var selectedKey = ShowSelectionDialog("请选择要授权使用的密钥:", "选择密钥", keyOptions);
                        if (string.IsNullOrEmpty(selectedKey))
                        {
                            return new AppAuthorizationResult { IsAuthorized = false };
                        }

                        // 处理用户选择
                        var result = new AppAuthorizationResult
                        {
                            IsAuthorized = true,
                            AuthorizedScopes = requestedScopes,
                            AuthorizedKeys = new List<KeyInfo>(),
                            SessionDurationMinutes = -1  // -1表示与连接绑定，断开连接时自动撤销
                        };

                        if (keyInfoMap.TryGetValue(selectedKey, out var keyInfo))
                        {
                            result.AuthorizedKeys.Add(keyInfo);
                        }

                        return result;
                    }
                    else
                    {
                        // 用户拒绝授权
                        return new AppAuthorizationResult { IsAuthorized = false };
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "显示应用授权对话框时发生异常");
                    return new AppAuthorizationResult { IsAuthorized = false };
                }
            });
        }

        /// <summary>
        /// 将权限范围翻译为中文
        /// </summary>
        private string TranslateScopeName(string scope)
        {
            return scope switch
            {
                "sign" => "签名操作",
                "verify" => "验证操作",
                "did" => "DID管理",
                "contract" => "区块链合约调用",
                "token" => "令牌签发",
                _ => scope
            };
        }

        /// <summary>
        /// 根据选择的索引获取会话时长（分钟）
        /// </summary>
        private int GetSessionDurationMinutes(int index)
        {
            return index switch
            {
                0 => 30,      // 30分钟
                1 => 60,      // 1小时
                2 => 480,     // 8小时
                3 => 1440,    // 24小时
                4 => 43200,   // 30天（直到手动撤销）
                _ => 60       // 默认1小时
            };
        }
    }
} 